package com.wgj.android.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.bumptech.glide.Glide;
import com.jiaai.xui.utils.XBitmapUtils;
import com.jiaai.xui.utils.XEmptyUtils;
import com.jiaai.xui.utils.http.ListHttpCallBack;
import com.jiaai.xui.utils.http.XHttp;
import com.jiaai.xui.utils.imageload.XImage;
import com.jiaai.xui.view.widget.XLoadingDialog;
import com.jiaai.xui.view.widget.XToast;
import com.jiaai.xui.view.widget.XTopbarView;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wgj.android.R;
import com.wgj.android.dialog.ShareDiadlog;
import com.wgj.android.entity.Card;
import com.wgj.android.entity.SystemConfg;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.ui.activity.CreateCardActivity;
import com.wgj.android.utils.CacheUtils;
import com.wgj.android.web.WGJWebActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class CardFragment extends Fragment implements ShareDiadlog.OnShareListener {
    @BindView(R.id.creaCard)
    TextView creaCard;
    @BindView(R.id.avater)
    ImageView avater;
    @BindView(R.id.tx_nickname)
    TextView txNickname;
    @BindView(R.id.tx_role)
    TextView txRole;
    @BindView(R.id.tx_unit)
    TextView txUnit;
    @BindView(R.id.tx_iphone)
    TextView txIphone;
    @BindView(R.id.tx_vx)
    TextView txVx;
    @BindView(R.id.tx_email)
    TextView txEmail;
    @BindView(R.id.tx_address)
    TextView txAddress;
    @BindView(R.id.linearLayout2)
    LinearLayout linearLayout2;
    @BindView(R.id.tv_cord)
    ImageView tvCord;
    @BindView(R.id.rootView)
    LinearLayout rootView;
    @BindView(R.id.tx_intro)
    TextView txIntro;
    @BindView(R.id.shareView)
    LinearLayout shareView;
    @BindView(R.id.image1)
    ImageView image1;
    @BindView(R.id.image2)
    ImageView image2;
    @BindView(R.id.image3)
    ImageView image3;
    @BindView(R.id.toShareBut)
    TextView toShareBut;
    @BindView(R.id.editCard)
    TextView editCard;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    @BindView(R.id.tv_renqi)
    TextView tvRenqi;
    @BindView(R.id.tv_zan)
    TextView tvZan;
    @BindView(R.id.tv_shoucang)
    TextView tvShoucang;
    @BindView(R.id.image)
    TextView image;
    @BindView(R.id.topBar)
    XTopbarView topBar;
    private View view;
    private Card card;
    private ShareDiadlog shareDiadlog;
    private SystemConfg confg;
    private IWXAPI api;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_card, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        topBar.setTopBarClickListener(new XTopbarView.OnTopBarClickListener() {
            @Override
            public void onBackClick() {
                getActivity().finish();
            }

            @Override
            public void onRightButClick() {
                WGJWebActivity.openHtml5(getActivity(),WGJAPI.WEB_URL+"/card/index.html#/card/edit/business?mId="+CacheUtils.getMember().getM_id(),false);

            }
        });
        shareDiadlog = new ShareDiadlog().setOnShareListener(this);
        confg = CacheUtils.getSystemConfig();
        api = WXAPIFactory.createWXAPI(getContext(), confg.getWXAppId(), true);
        api.registerApp(confg.getWXAppId());
        getMyCard();
    }

    @OnClick({R.id.creaCard, R.id.editCard})
    public void creadCard(View v) {
        Intent intent = new Intent(getContext(), CreateCardActivity.class);
        switch (v.getId()) {
            case R.id.creaCard:
                startActivityForResult(intent, 1);
                break;
            case R.id.editCard:

                intent.putExtra("card", (Serializable) card);
                startActivityForResult(intent, 1);
                break;
        }

    }

    public void getMyCard() {
        XLoadingDialog.with(getContext()).show();
        XHttp.obtain().get(WGJAPI.getMyCard(), null, new ListHttpCallBack<Card>() {
            @Override
            public void onSuccess(List<Card> list) {
                if (list.get(0).getMId() == null) {
                    creaCard.setVisibility(View.VISIBLE);
                    scrollView.setVisibility(View.GONE);
                } else {
                    scrollView.setVisibility(View.VISIBLE);
                    creaCard.setVisibility(View.GONE);
                    card = list.get(0);
                   /* Even even =new Even();
                    even.setId(card.getId()+"");
                    EventBus.getDefault().postSticky(even);*/
                    setData();
                }
                XLoadingDialog.with(getContext()).dismiss();
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                XLoadingDialog.with(getContext()).dismiss();
            }
        });
    }

    private void setData() {
        Glide.with(getContext()).load(WGJAPI.getShareCardUrl(card.getId() + "")).into(tvCord);
        Log.i("tianyun", WGJAPI.getShareCardUrl(card.getId() + ""));
        XImage.getInstance().load(avater, card.getAvatar());
        txRole.setText(card.getRole());
        txUnit.setText(card.getUnit());
        txNickname.setText(card.getNickname());
        txIphone.setText(card.getIphone());
        txIphone.setTextColor((card.getModel() == null) ? Color.parseColor("#FF9933") : Color.parseColor(card.getModel()));
        txVx.setText(card.getVx());
        txEmail.setText(card.getEmail());
        txAddress.setText(card.getAddress());
        txIntro.setText(card.getIntro());
        tvRenqi.setText("人气" + card.getClick());
        tvShoucang.setText("收藏" + card.getCountCollection());
        tvZan.setText("点赞" + card.getCountLike());
        if (card.getImg() != null) {
            JSONArray array = JSONArray.parseArray(card.getImg());
            if (array.size() == 1) {
                image1.setVisibility(View.VISIBLE);
                XImage.getInstance().load(image1, array.getString(0));
                image2.setVisibility(View.GONE);
                image3.setVisibility(View.GONE);
            }
            if (array.size() == 2) {
                image1.setVisibility(View.VISIBLE);
                image2.setVisibility(View.VISIBLE);
                XImage.getInstance().load(image1, array.getString(0));
                XImage.getInstance().load(image2, array.getString(1));
                image3.setVisibility(View.GONE);
            }
            if (array.size() == 3) {
                image1.setVisibility(View.VISIBLE);
                image2.setVisibility(View.VISIBLE);
                image3.setVisibility(View.VISIBLE);
                XImage.getInstance().load(image1, array.getString(0));
                XImage.getInstance().load(image2, array.getString(1));
                XImage.getInstance().load(image3, array.getString(2));
            }
        } else {
            image.setVisibility(View.VISIBLE);
        }
        //txEmail.setText(card.get);
    }

    @OnClick(R.id.toShareBut)
    public void onShare(View view) {
        shareDiadlog.show(getChildFragmentManager(), "shareDialog");

    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1000) {
            getMyCard();
        }
    }

    @Override
    public void onShareQQ() {
        XToast.error("暂未开放");
    }

    @Override
    public void onShareWeiXin() {
        if (XEmptyUtils.isSpace(confg.getWXAppId())) {
            XToast.error("暂未开放");
        } else {
            Bitmap bitmap = loadBitmapFromView();
            WXImageObject imgWX = new WXImageObject(bitmap);
            WXMediaMessage mediaMessage = new WXMediaMessage();
            mediaMessage.mediaObject = imgWX;
            Bitmap th = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * 0.3), (int) (bitmap.getHeight() * 0.3), true);
            bitmap.recycle();
            mediaMessage.thumbData = XBitmapUtils.getBytesFromBitmap(th);
            th.recycle();
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("img");
            req.message = mediaMessage;
            req.scene = 0;
            api.sendReq(req);
        }
    }

    @Override
    public void onShareFriends() {
        if (XEmptyUtils.isSpace(confg.getWXAppId())) {
            XToast.error("暂未开放");
        } else {
            Bitmap bitmap = loadBitmapFromView();
            WXImageObject imgWX = new WXImageObject(bitmap);
            WXMediaMessage mediaMessage = new WXMediaMessage();
            mediaMessage.mediaObject = imgWX;
            Bitmap th = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * 0.3), (int) (bitmap.getHeight() * 0.3), true);
            bitmap.recycle();
            mediaMessage.thumbData = XBitmapUtils.getBytesFromBitmap(th);
            th.recycle();
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("webpage");
            req.message = mediaMessage;
            req.scene = 1;
            api.sendReq(req);
        }
    }

    @Override
    public void onShareSpaceBut() {
        XToast.error("暂未开放");
    }

    @Override
    public void onlinkButBut() {
        XToast.error("暂未开放");
    }

    private Bitmap loadBitmapFromView() {
        int w = shareView.getWidth();
        int h = shareView.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);

        //shareView.layout(0, 0, w, h);
        shareView.draw(c);

        return bmp;
    }

    private static String buildTransaction(String type) {
        return type == null ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(TemplateFragment.Event event) {
        GradientDrawable drawable = new GradientDrawable();
        drawable.setCornerRadius(14);
        //drawable.setColor(event.getI());
        drawable.setStroke(4, Color.parseColor(event.getColor()));
        shareView.setBackground(drawable);
        txIphone.setTextColor(Color.parseColor(event.getColor()));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    public class Even {
        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        String id;
    }
}
